package com.star.rpc.loadbalancer;

import cn.hutool.core.collection.CollUtil;
import com.star.rpc.modal.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * packageName com.star.rpc.loadbalancer
 *
 * @author zerostart
 * @className RoundRobinLoadBalancer
 * @date 2024/12/7
 * @description
 */
public class RoundRobinLoadBalancer implements LoadBalancer{


    private final AtomicInteger currentIndex = new AtomicInteger(0);


    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if (CollUtil.isEmpty(serviceMetaInfoList)) {
            return null;
        }
        // 只有一个无需轮询
        int size = serviceMetaInfoList.size();
        if (size == 1) {
            return serviceMetaInfoList.get(0);
        }
        // 取模算法查询
        int index = currentIndex.getAndIncrement() % size;
        return serviceMetaInfoList.get(index);
    }
}
